package cn.lx.stack;

import cn.lx.stack.Stack;

import java.util.Iterator;

/**使用链表实现下压栈
 * Created by Administrator on 2017/3/21 0021.
 */
public class  MyNodeStack<Item> implements Stack<Item>,Iterable<Item>{


    int N = 0;//链表长度
    Node first;//链表首节点

    @Override
    public Iterator iterator() {
        return new MyNodeStackIterator();
    }
    private class MyNodeStackIterator implements Iterator<Item>{
        int i = N;
        private Node next = first;
        @Override
        public boolean hasNext() {
            return i>0;
        }

        @Override
        public Item next() {
            Item item = next.item;
            next = next.next;
            i--;
            return item;
        }
    }
    private class Node{
        Item item;
        Node next;
    }

    @Override
    public Item pop() {
        if(N == 0){
            return  null;
        }
        N--;
        Item item = first.item;

        first = first.next;

        return item;
    }

    @Override
    public void push(Item item) {
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
        N++;
    }

    @Override
    public boolean isEmpty() {
        return N == 0;
    }

    @Override
    public int size() {
        return N;
    }

    public static void main(String[] args) {
        MyNodeStack<String> stack = new MyNodeStack<>();
        stack.push("1");
        stack.push("2");
        stack.push("3");
        for(String s : stack){
            System.out.println(s);
        }
    }
}
